import type {MessageOptions} from 'naive-ui';
import {createDiscreteApi} from 'naive-ui';

const { message } = createDiscreteApi(['message']);

/**
 * 警告消息
 *
 * @param messageStr
 * @param options
 */
export function warningMessage(messageStr: string, options?: MessageOptions) {
  message.warning(messageStr, options);
}

/**
 * 错误消息
 *
 * @param messageStr
 * @param options
 */
export function errorMessage(messageStr: string, options?: MessageOptions) {
  message.error(messageStr, options);
}

/**
 * 成功消息
 *
 * @param messageStr
 * @param options
 */
export function successMessage(messageStr: string, options?: MessageOptions) {
  message.success(messageStr, options);
}

/**
 * 普通消息
 *
 * @param messageStr
 * @param options
 */
export function infoMessage(messageStr: string, options?: MessageOptions) {
  message.info(messageStr, options);
}

/** 将一个对象先转为字符串 */
export interface Params {
  [propName: string]: any;
}
export function getStringWithParams(params: Params) {
  let index: number = 0;
  let urlStr: string = '';
  for (const item in params) {
    if (index === 0) {
      urlStr += `?${item}=${params[item]}`;
    } else {
      urlStr += `&${item}=${params[item]}`;
    }
    index += 1;
  }
  return urlStr;
}

/** 将字符串转为一个对象 */
export function getObjectWithScene(string: string) {
  if (JSON.stringify(string) === '{}') {
    return {};
  }
  const stringArr: string[] = string.split('&');
  const obj: any = {};
  for (let i: number = 0; i < stringArr.length; i += 1) {
    const item: string = stringArr[i];
    const index: number = item.indexOf('=');
    const key: string = item.substring(0, index);
    obj[key] = item.substring(index + 1, item.length);
  }
  // stringArr.map((item: string) => {
  //   const index: number = item.indexOf('=');
  //   const key: string = item.substring(0, index);
  //   obj[key] = item.substring(index + 1, item.length);
  // })
  return obj;
}

/** 将一个字符串按照指定长度切片 */
export function sliceStringByLength(string: string, length: number) {
  const result: string[] = [];
  for (let i = 0; i < string.length; i += length) {
    result.push(string.substr(i, length));
  }
  return result;
}

/** 获取字符的像素宽度 */
export function getStringLengthPx(str: string, font_size: number): number {
  const str_length = str.replace(/[^\x20-\xFF]/gi, 'ac').length;
  return (str_length * font_size) / 2;
}

/**
 * 生成一个n位的随机id
 *
 * @param {number | string} length 随机字符串的长度
 * @param {string} type
 */
export function generateRandomCode(length: number, type = 'numEML'): string {
  if (length <= 0) return '';

  const selectData: { [propName: string]: any } = {
    num: '0123456789',
    engM: 'abcdefghijklmnopqrstuvwxyz',
    engL: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    numEM: '0123456789abcdefghijklmnopqrstuvwxyz',
    numEL: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    engML: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
    numEML: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  };
  const data = selectData[type];
  const len = data.length;
  let codes = '';
  for (let i = 0; i < length; i += 1) {
    const r = Number.parseInt(`${Math.random() * len}`, 10);
    codes += data[r];
  }
  return codes;
}

/**
 * 获取当前格式化时间(年月日时分) YYYY-MM-DD hh:mm:ss
 *
 * @returns {string}
 */
export function getNowFormatDate() {
  const date = new Date();
  const space1 = '-';
  const space2 = ':';
  const month = `0${date.getMonth() + 1}`.slice(-2);
  const strDate = `0${date.getDate()}`.slice(-2);
  return `${
    date.getFullYear() + space1 + month + space1 + strDate
  } ${date.getHours()}${space2}${date.getMinutes()}${space2}${date.getSeconds()}`;
}

/**
 * 获取当前格式化时间(时分秒) hh:mm:ss
 *
 * @returns {string}
 */
export function getNowTimeDate() {
  const date = new Date();
  const space2 = ':';
  return `${date.getHours()}${space2}${date.getMinutes()}${space2}${date.getSeconds()}`;
}

/**
 * 获取图片信息
 * @param url
 * @param callback
 */
export function getImageInfoByUrl(url: string, callback: any) {
  const img = new Image();
  img.onload = () => {
    const imageInfo = {
      width: img.width,
      height: img.height,
      aspectRatio: img.width / img.height
    };
    callback(imageInfo);
  };
  img.onerror = () => {
    callback(null);
  };
  img.src = url;
}

/**
 * 将图片转换为base64
 * @param url
 */
export function convertImageToBase64(url: string) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = () => {
      const reader = new FileReader();
      reader.onloadend = () => {
        resolve(reader.result);
      };
      reader.onerror = reject;
      reader.readAsDataURL(xhr.response);
    };
    xhr.onerror = reject;
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  });
}

/**
 * 从base64中获取图片信息
 * @param base64String
 */
export function getImageInfoFromBase64(base64String: string) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve({
        width: img.width,
        height: img.height,
        type: base64String.split(';')[0].split(':')[1]
      });
    };
    img.onerror = () => {
      reject(new Error('图片加载失败'));
    };
    img.src = base64String;
  });
}

/**
 * 转义html内容
 *
 * @param html
 */
export function escapeHTMLManually(html: string) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return html.replace(/[&<>"']/g, (m: string) => {
    return map[m];
  });
}
